﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Text;

using BartonExtension;

namespace WSServer
{
    public enum WSSocketStatus
    {
        kSocketIntializing,
        kSocketInitialized,
        kSocketStatusAuthorized,
        kSocketStatusTokenExpired,
        kSocketStatusClosed
    }
    public class WSSocket
    {
        const int MAX_MESSAGES_POOL_SIZE = 100;
        const int STATE_TIMEOUT = 30 * 1000; //in sec

        const int BUFFER_SIZE = 1024;
        private WebSocket socket { get; set; }
        private double socket_status_on_changed_timetag { get; set; }
        private bool disposed = false;
        private Task pushTask { get; set; }
        private Timer timeoutMonitor { get; set; }

        public WSSocketMessagePool messagePool { get; set; }
        public WSAccessToken token { get; set; }
        public string identifier { get; set; }
        public bool pushingMessage { get; set; }
        public WSSocketStatus socket_status { get; set; }

        public void Dispose()
        {
            if(!disposed)
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            if (disposing)
            {
                // 清理托管资源
                if (socket != null)
                {
                    if(timeoutMonitor != null)
                    {
                        timeoutMonitor.Dispose();
                        timeoutMonitor = null;
                    }
                    if(pushTask != null)
                    {
                        pushTask.Dispose();
                        pushTask = null;
                    }
                    if(socket != null)
                    {
                        try
                        {
                            socket.Abort();
                            socket.Dispose();
                            socket = null;
                        }
                        catch(Exception)
                        {

                        }
                    }
                    if(token != null)
                    {
                        token.Dispose();
                        token = null;
                    }
                }
            }
            disposed = true;
        }

        public static WSSocket New(WebSocket socket)
        {
            WSSocket ws = new WSSocket(socket);
            return ws;
        }
        public WSSocket(WebSocket socket)
        {
            this.socket = socket;
            Initialize();
        }
        public void Initialize()
        {
            if(socket.State == WebSocketState.Open)
            {
                OnOpen();
            }
        }
        public Task RegisterSocketEvents()
        {
            return Task.Factory.StartNew(() =>
                {
                    while (!this.disposed || this.socket_status != WSSocketStatus.kSocketStatusClosed)
                    {
                        ReceiveData();
                    }
                });
        }
        private void ReceiveData()
        {
            try
            {
                bool endOfData = false;
                List<ArraySegment<byte>> data = new List<ArraySegment<byte>>();
                int offset = 0;
                WebSocketMessageType messageType = WebSocketMessageType.Text;
                while (!endOfData)
                {
                    ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[BUFFER_SIZE]);
                    var recvTask = socket.ReceiveAsync(
                            buffer, CancellationToken.None);
                    recvTask.Wait();
                    var result = recvTask.Result;
                    messageType = result.MessageType;
                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        WSSocketCollection.collection.DeleteSocket(this);
                        return;
                    }
                    endOfData = result.EndOfMessage;
                    offset += result.Count;
                    data.Add(buffer);
                }
                if (data.Count > 0)
                {
                    byte[] receiveBuffer = data[0].Array;
                    for (int i = 1; i < data.Count; i++)
                    {
                        receiveBuffer = receiveBuffer.Concat(data[i].Array).ToArray();
                    }
                    ArraySegment<byte> recvData = new ArraySegment<byte>(receiveBuffer, 0, offset);
                    ProcessRecvData(recvData, messageType).Wait();
                }
            }
            catch(WebSocketException ex)
            {
                OnClose(null, "");
            }
            catch(Exception)
            {

            }
        }
        private async Task ProcessRecvData(ArraySegment<byte> message,WebSocketMessageType type)
        {
            if (socket.State == WebSocketState.Open)
            {
                await OnMessageReceived(message, type);
            }
            else if (socket.State == WebSocketState.Closed)
            {
                OnClose(socket.CloseStatus, socket.CloseStatusDescription);
            }
            else if (socket.State == WebSocketState.CloseReceived)
            {
                OnClose(socket.CloseStatus, socket.CloseStatusDescription);
            }
        }
        private async Task OnMessageReceived(ArraySegment<byte> message,WebSocketMessageType type)
        {
            WSMessage ws_msg = new WSMessage()
            {
                message_time = DateTime.Now,
                message_type = type,
                content = message,
                socket = this
            };
            var result = await WSUtils.sharedInstance.ProcessMessage(ws_msg,
                msg_onRegisterService =>
                {
                    SetCurrentSocketStatus(WSSocketStatus.kSocketStatusAuthorized);
                    WSConnectionIndexer.IndexConnections(new WSSocket[] { this }.ToList());
                    messagePool = new WSSocketMessagePool(this.identifier);

                    WSResponse response = new WSResponse()
                    {
                        identifier = this.identifier,
                        token = this.token,
                        type = WSResponseType.kWSResponseTypeDidSocketRegistered
                    };
                    Send<WSResponse>(response).Wait();

                    messagePool.RestoreResponsesToStorage(new WSStorage("socket_cache"), token);

                    if (messagePool.Count > 0)
                    {
                        PushToClient();
                    }
                },
                msg_onRequestToken =>
                {
                    this.AssignAccessCodeToSocket();
                    WSResponse response = new WSResponse()
                    {
                        identifier = this.identifier,
                        token = this.token,
                        type = WSResponseType.kWSResponseTypeDidTokenRefreshed
                    };
                    Send<WSResponse>(response).Wait();
                },
                msg_onRegisteredSuccess =>
                {
                },
                msg_onReceviceMessage =>
                {

                },
                msg_onReceiveMessageReceip =>
                {
                    WSRequest request = ws_msg.Get<WSRequest>();
                    messagePool.didReceiveMessageRecip(request);
                });
            if (!result.isProcessedSuccess)
            {
                
            }
        }
        private void OnOpen()
        {
            this.AssignAccessCodeToSocket();
            WSSocketCollection.collection.Enqueue(this);
            SetCurrentSocketStatus(WSSocketStatus.kSocketInitialized);
        }
        private void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
        {
            SetCurrentSocketStatus(WSSocketStatus.kSocketStatusClosed);
            if(this.messagePool != null)
                this.messagePool.CacheResponsesToStorage(new WSStorage("socket_cache"));
            WSSocketCollection.collection.DeleteSocketWithIdentifier(this.identifier);
        }
        private void SetCurrentSocketStatus(WSSocketStatus status)
        {
            socket_status = status;
            socket_status_on_changed_timetag = DateTime.Now.GetTimeIntervalFrom1970WithDateTime();
        }
        public void EnqueueMessage(WSResponse response)
        {
            messagePool.addMessage(response);
            PushToClient();
        }
        public void PushToClient()
        {
            if (this.socket_status != WSSocketStatus.kSocketStatusAuthorized)
                return;
            

            if(pushTask == null)
            {
                pushTask = new Task(() =>
                {
                    doPush();
                });
            }
            else
            {
                if (pushTask.IsCompleted)
                {
                    pushTask.Dispose();
                    pushTask = null;
                    this.pushingMessage = false;
                    PushToClient();
                    return;
                }
                pushTask.ContinueWith((t) =>
                    {
                        doPush();
                    });
            }
            if(pushTask.Status != TaskStatus.Running && !pushTask.IsCompleted)
                pushTask.Start();
        }
        private void doPush()
        {
            if (!this.pushingMessage)
            {
                this.pushingMessage = true;
                //Take one
                lock (messagePool)
                {
                    WSResponse response = messagePool.GetFirstResponse();
                    if (response != null)
                    {
                        this.Send<WSResponse>(response).Wait();
                        response.status = WSResponseStatus.kWSResponseStatusSentButWatingReceip;
                        PushToClient();
                    }
                }
            }
        }
        private Task Send<T>(T obj)
        {
            if(this.socket.State != WebSocketState.Open)
            {
                return Task.Factory.StartNew(() => { });
            }
            try
            {
                string sendMessage = string.Empty;
                if (typeof(T) == typeof(int) || typeof(T) == typeof(string))
                    sendMessage = obj.ToString();
                else
                    sendMessage = obj.ToJson();
                var toSend = Encoding.UTF8.GetBytes(sendMessage);

                Task t = this.socket.SendAsync(new ArraySegment<byte>(toSend), WebSocketMessageType.Text, true, CancellationToken.None);
                return t;
            }
            catch (Exception e)
            {
                OnClose(WebSocketCloseStatus.InternalServerError, e.Message);
                return Task.Factory.StartNew(() => { });
            }
        }
        public bool ShouldBeCleaned()
        {
            if (this.socket_status == WSSocketStatus.kSocketStatusClosed)
                return true;
            if(this.socket_status == WSSocketStatus.kSocketStatusTokenExpired && (DateTime.Now.GetTimeIntervalFrom1970WithDateTime() - socket_status_on_changed_timetag) >= STATE_TIMEOUT)
                return true;
            if (this.socket_status == WSSocketStatus.kSocketIntializing && (DateTime.Now.GetTimeIntervalFrom1970WithDateTime() - socket_status_on_changed_timetag) >= STATE_TIMEOUT)
                return true;
            if (this.socket_status == WSSocketStatus.kSocketInitialized && (DateTime.Now.GetTimeIntervalFrom1970WithDateTime() - socket_status_on_changed_timetag) >= STATE_TIMEOUT)
                return true;
            return false;
        }
        public void onTokenExpired(WSAccessToken token)
        {
            WSResponse response = new WSResponse()
            {
                type = WSResponseType.kWSResponseTypeDidTokenExpired,
                identifier = this.identifier,
                token = token,
                timetag = DateTime.Now
            };
            WSUtils.sharedInstance.SendMessageToWSSocketWithIdentifier(this.identifier, response);
        }
    }
}
